﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VoL.Domain.Infrastructure;
using VoL.Domain.IServices.DoctorManage;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
namespace VoL.Domain.Services.DoctorManage
{
    public class DoctorManageServices : IDoctorManageServices
    {
        /// <summary>
        /// 出量仓储
        /// </summary>
        private readonly IBaseRepository<OutRecord> _outRecordbaseRepository;
        /// <summary>
        /// 入量仓储
        /// </summary>
        private readonly IBaseRepository<InRecord> _recordRepository;
        /// <summary>
        /// 患者仓储
        /// </summary>
        private readonly IBaseRepository<Patient> _patientRepository;
        /// <summary>
        /// 护理记录仓储
        /// </summary>
        private readonly IBaseRepository<PatientReCord> _patientReCordRepository;
        /// <summary>
        /// 医嘱仓储
        /// </summary>
        private readonly IBaseRepository<Tell> _tellRepository;
        /// <summary>
        /// 床位仓储
        /// </summary>
        private readonly IBaseRepository<Bed> _bedRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_outRecordbaseRepository">出量仓储</param>
        /// <param name="recordRepository">入量仓储</param>
        /// <param name="patientRepository">患者仓储</param>
        /// <param name="patientReCordRepository">护理记录仓储</param>
        /// <param name="tellRepository">医嘱仓储</param>
        /// <param name="bedRepository">床位仓储</param>
        public DoctorManageServices(IBaseRepository<OutRecord> _outRecordbaseRepository, IBaseRepository<InRecord> recordRepository, IBaseRepository<Patient> patientRepository, IBaseRepository<PatientReCord> patientReCordRepository, IBaseRepository<Tell> tellRepository, IBaseRepository<Bed> bedRepository)
        {
            this._outRecordbaseRepository = _outRecordbaseRepository;
            this._recordRepository = recordRepository;
            this._patientRepository = patientRepository;
            this._patientReCordRepository = patientReCordRepository;
            this._tellRepository = tellRepository;
            _bedRepository = bedRepository;
        }

        /// <summary>
        /// 获取入量
        /// </summary>
        /// <param name="patientCode">患者编号</param>
        /// <param name="firstTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>返回</returns>
        public Task<WebResponseContent> GetInRecords(string patientCode, DateTime? firstTime, DateTime? endTime)
        {
            var result = new WebResponseContent();

            var inRecordlist = _recordRepository.GetAll(m => m.PatientCode == patientCode);
            inRecordlist = inRecordlist.WhereIF(firstTime != null, m => m.ADItDate >= firstTime);
            inRecordlist = inRecordlist.WhereIF(endTime != null, m => m.ADItDate <= endTime || m.ADItDate < endTime.Value.AddDays(1));
            result.OK("查询入量成功", inRecordlist);
            return Task.FromResult(result);
        }

        /// <summary>
        /// 获取出量
        /// </summary>
        /// <param name="patientCode">患者编号</param>
        /// <param name="firstTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>返回</returns>
        public Task<WebResponseContent> GetOutRecords(string patientCode, DateTime? firstTime, DateTime? endTime)
        {
            var result = new WebResponseContent();
            var outRecordlist = _outRecordbaseRepository.GetAll(m => m.PatientCode == patientCode);
            outRecordlist = outRecordlist.WhereIF(firstTime != null, m => m.OutDate >= firstTime);
            outRecordlist = outRecordlist.WhereIF(endTime != null, m => m.OutDate <= endTime || m.OutDate < endTime.Value.AddDays(1));
            result.OK("查询出量成功", outRecordlist);
            return Task.FromResult(result);
        }

        /// <summary>
        /// 获取患者信息
        /// </summary>
        /// <returns>返回</returns>
        public Task<WebResponseContent> GetPatients()
        {
            var result = new WebResponseContent();
            var patientlist = _patientRepository.GetAll();
            result.OK("查询患者信息成功", patientlist.ToList());
            return Task.FromResult(result);
        }

        /// <summary>
        /// 查询日常护理记录表
        /// </summary>
        /// <param name="patientCode">患者编号</param>
        /// <returns>返回</returns>
        public Task<WebResponseContent> GetPatientReCords(string patientCode)
        {
            var result = new WebResponseContent();
            var patientReCordlist = _patientReCordRepository.GetAll(m => m.PatientCode == patientCode);
            result.OK("查询日常护理成功", patientReCordlist);
            return Task.FromResult(result);
        }

        /// <summary>
        /// 根据患者编号查询患者信息成功
        /// </summary>
        /// <returns>返回</returns>
        public Task<WebResponseContent> GetPatientsByPatientCode(string patientCode)
        {
            var result = new WebResponseContent();
            var patientlist = _patientRepository.GetAll(m => m.PatientCode == patientCode);
            result.OK("根据患者编号查询患者信息成功", patientlist);
            return Task.FromResult(result);
        }

        /// <summary>
        /// 创建医嘱
        /// </summary>
        /// <param name="tell">医嘱信息</param>
        /// <returns>返回创建结果</returns>
        public async Task<WebResponseContent> CreateTell(Tell tell)
        {
            var result = new WebResponseContent();
            if (tell == null)
            {
                result.Error("医嘱信息不能为空");
                return await Task.FromResult(result);
            }

            tell.IsDelete = 0;
            tell.IsPublisher = 0;
           var t= await _tellRepository.Add(tell);
            if (t > 0)
            {
                result.OK("创建医嘱成功");
            }
            else 
            {
                result.OK("创建医嘱失败");
            }
           
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 删除医嘱（软删除）
        /// </summary>
        /// <param name="id">医嘱ID</param>
        /// <returns>返回删除结果</returns>
        public async Task<WebResponseContent> DeleteTell(int id)
        {
            var result = new WebResponseContent();
            if (id <= 0)
            {
                result.Error("医嘱ID无效");
                return await Task.FromResult(result);
            }

            var tell = _tellRepository.GetAll().FirstOrDefault(x => x.Id == id && x.IsDelete == 0);
            if (tell == null)
            {
                result.Error("医嘱不存在");
                return await Task.FromResult(result);
            }

            tell.IsDelete = 1;
            _tellRepository.Update(tell);
            result.OK("删除医嘱成功");
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 更新医嘱
        /// </summary>
        /// <param name="tell">医嘱信息</param>
        /// <returns>返回更新结果</returns>
        public async Task<WebResponseContent> UpdateTell(Tell tell)
        {
            var result = new WebResponseContent();
            if (tell == null || tell.Id <= 0)
            {
                result.Error("医嘱信息无效");
                return await Task.FromResult(result);
            }

            var existingTell = _tellRepository.GetAll().FirstOrDefault(x => x.Id == tell.Id && x.IsDelete == 0);
            if (existingTell == null)
            {
                result.Error("医嘱不存在");
                return await Task.FromResult(result);
            }

            // 更新医嘱信息
            existingTell.DoctorCode = tell.DoctorCode;
            existingTell.BedCode = tell.BedCode;
            existingTell.PatientCode = tell.PatientCode;
            existingTell.DoctorContent = tell.DoctorContent;
            existingTell.DoctorSTime = tell.DoctorSTime;
            existingTell.DoctorETime = tell.DoctorETime;
            existingTell.IsPublisher = tell.IsPublisher;

            var updateResult = await _tellRepository.Update(existingTell);
            if (updateResult > 0)
            {
                result.OK("更新医嘱成功");
            }
            else
            {
                result.Error("更新医嘱失败");
            }

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 获取医嘱列表（支持模糊查询）
        /// </summary>
        /// <param name="patientCode">患者编号（支持模糊查询）</param>
        /// <returns>返回医嘱列表</returns>
        public async Task<WebResponseContent> GetTells(string? patientCode)
        {
            var result = new WebResponseContent();
            try
            {
                var queryTell = _tellRepository.GetAll().Where(x => x.IsDelete == 0);

                // 患者编号模糊查询 
                queryTell = queryTell.WhereIF(!string.IsNullOrEmpty(patientCode),m => m.PatientCode.Contains(patientCode)); 

                // 按时间降序排序

                result.OK("查询医嘱成功", queryTell);
            }
            catch (Exception ex)
            {
                result.Error($"查询医嘱失败：{ex.Message}");
            }

            return result;
        }


        /// <summary>
        /// 修改发布状态
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>返回</returns>
        public async Task<WebResponseContent> Updatesatus(int id)
        {
            var result = new WebResponseContent();
            try
            {
                var status = _tellRepository.GetAll().FirstOrDefault(m => m.Id == id && m.IsPublisher==0); 
                if (status !=null)
                {
                    status.IsPublisher = 1;
                }
                await _tellRepository.Update(status);
                result.OK("查询医嘱成功", status);
                return result;
            }
            catch (Exception ex)
            {
                result.Error($"修改状态失败：{ex.Message}");
                return result;
            }
        }


        /// <summary>
        /// 获取医嘱列表（支持模糊查询）
        /// </summary>
        /// <param name="patientCode">患者编号（支持模糊查询）</param>
        /// <returns>返回医嘱列表</returns>
        public async Task<WebResponseContent> GetTellsPublisher(string? patientCode)
        {
            var result = new WebResponseContent();
            try
            {
                var queryTell = _tellRepository.GetAll().Where(m => m.IsDelete == 0&&m.IsPublisher==1);
                // 患者编号模糊查询 
                queryTell = queryTell.WhereIF(!string.IsNullOrEmpty(patientCode), m => m.PatientCode.Contains(patientCode));

                // 按时间降序排序

                result.OK("查询医嘱成功", queryTell);
            }
            catch (Exception ex)
            {
                result.Error($"查询医嘱失败：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 床位
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> GetBed()
        {
            var result = new WebResponseContent();
            var bedList = _bedRepository.GetAll().ToList();
            result.OK("查询床位成功",bedList);
            return result; 
        } 


    }
}
